package com.lagou.handler;

import com.lagou.service.RpcRequest;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        RpcRequest rpcRequest = (RpcRequest) msg;
        Object serviceHandler = SpringUtil.getBean(rpcRequest.getClassName());
        if(serviceHandler!=null) {
            Method[] methods = serviceHandler.getClass().getMethods();
            for (Method method:methods) {
                if(method.getName().equals(rpcRequest.getMethodName())) {
                   Object result = method.invoke(serviceHandler, rpcRequest);
                   ctx.writeAndFlush((String) result);
                }
            }
        }
        


    }
}
